package com.hengtiansoft.lfy.fragment;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.reflect.TypeToken;
import com.hengtiansoft.lfy.R;
import com.hengtiansoft.lfy.activity.Change_SceneDetailsActivity;
import com.hengtiansoft.lfy.adapter.Change_SceneTypeAdapter;
import com.hengtiansoft.lfy.adapter.NewsAdapter;
import com.hengtiansoft.lfy.base.BaseFragment;
import com.hengtiansoft.lfy.been.Child;
import com.hengtiansoft.lfy.constants.Constants;
import com.hengtiansoft.lfy.db.CL_InviteMessgeDao;
import com.hengtiansoft.lfy.download.DownloadManager;
import com.hengtiansoft.lfy.entity.CategroyEntity;
import com.hengtiansoft.lfy.entity.ServiceResult;
import com.hengtiansoft.lfy.net.NetHelper;
import com.hengtiansoft.lfy.net.NetUtils;
import com.hengtiansoft.lfy.utils.Config;
import com.hengtiansoft.lfy.utils.UnzipFromDir;
import com.hengtiansoft.lfy.widget.MyToast;
import com.hengtiansoft.lfy.widget.YesNoDialog;
import com.umeng.socialize.media.Constant;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;


/**
 * 场景页面
 */

public class ScenceFragment extends BaseFragment {


    public static final String EXTRA_CATEGROY = "categroy";
    public static final int CATEGROY_G20 = 1;
    public static final String REQUEST_G20 = "onee";
    public static final int CATEGROY_NORMAL = 2;
    public static final String REQUEST_NORMAL = "one";

    private Integer categroyId;
    private String request_categroy;

    private TextView tv_title;
    private ImageView iv_download_all;
    private ListView listview_categroy;
    private ArrayList<HashMap<String, Object>> mList = new ArrayList<>();
    private Change_SceneTypeAdapter sceneTypeAdapter;
    private String TAG = "Change_SceneFragment";
    private CL_InviteMessgeDao cL_InviteMessgeDao;
    private List<Child> dbChildList = null;
    private BroadcastReceiver mItemViewListClickReceiver;
    private String tempTimer="";
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_scence, container,   //fragment_conversation_scene
                false);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mItemViewListClickReceiver != null) {
            getActivity().unregisterReceiver(mItemViewListClickReceiver);
        }
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        categroyId = CATEGROY_NORMAL;
        request_categroy = REQUEST_NORMAL;
        cL_InviteMessgeDao = new CL_InviteMessgeDao(getActivity());
        zhuceguangbo();
        listview_categroy = (ListView) getView().findViewById(R.id.listview_categroy);
        /* todo转移
        iv_download_all = (ImageView) getView().findViewById(R.id.iv_download_all);
        iv_download_all.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new YesNoDialog.Builder(getActivity())
                        .setMessage(getString(R.string.downloadALL_title))
                        .setPositiveButton(getString(R.string.yes), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                if (!isdownload) {
                                    downloadALL();
                                }
                                dialog.dismiss();
                            }
                        })
                        .setNegativeButton(getString(R.string.no), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        })
                        .create().show();
            }
        });*/
        dbChildList = cL_InviteMessgeDao.getChildByCategroyId(categroyId);
        if (dbChildList.size() > 0) {
            mList.clear();
            for (int i = 0; i < dbChildList.size(); i++) {
                HashMap<String, Object> map = new HashMap<String, Object>();
                map.put("text", dbChildList.get(i).getName());
                map.put("id", dbChildList.get(i).getId());
                map.put("downLoadSize", dbChildList.get(i).getSize());
                map.put("downLoadCount", dbChildList.get(i).getRemark());
                map.put("child_img_url", dbChildList.get(i).getImagepath());
                map.put("isneedUpdate", dbChildList.get(i).getIsneedUpdate());
                map.put("zip_name", dbChildList.get(i).getZip_name());
                map.put("download_type", dbChildList.get(i).getDownload_type());
                map.put("time", dbChildList.get(i).getCreate_time());
                mList.add(map);
            }
        }
        getchildCategroyFromServer( getActivity());

        Log.d("tag", "mList.size = " + mList.size());

        sceneTypeAdapter = new Change_SceneTypeAdapter(getActivity(), mList,categroyId);
        listview_categroy.setAdapter(sceneTypeAdapter);
        sceneTypeAdapter.setAdapterListener(new Change_SceneTypeAdapter.SceneTypeAdapterListener() {

            @Override
            public void onItemClick(int position) {
                //跳转场景详情页面 Bundle[{from=detail, title=餐馆, childId=3, categroyId=1}]
                Intent intent = new Intent(getActivity(),
                        Change_SceneDetailsActivity.class);
                intent.putExtra("childId",
                        (Integer) sceneTypeAdapter.getItem(position).get("id"));
                intent.putExtra("from", "detail");
                intent.putExtra("isneedUpdate", sceneTypeAdapter.getItem(position).get("isneedUpdate") + "");
                intent.putExtra("categroyId", categroyId);
                intent.putExtra("title", sceneTypeAdapter.getItem(position)
                        .get("text").toString());
                startActivity(intent);
            }
            /*
            @Override
            public void onDownItemClick(int position, View v) {
                //点击下载
                String download_type = sceneTypeAdapter.getItem(position).get("download_type").toString();
                if (sceneTypeAdapter.getItem(position).get("zip_name") == null) {
                    Toast.makeText(getActivity(), getString(R.string.not_has_OfflineInstaller), Toast.LENGTH_LONG).show();
                    return;
                } else {
                    String zip_name = sceneTypeAdapter.getItem(position).get("zip_name").toString();

                    ImageView down_img_id = (ImageView) v.findViewById(R.id.down_img_id);
                    down_img_id.setVisibility(View.GONE);
                    TextView jindu = (TextView) v.findViewById(R.id.jindu_id);
                    jindu.setVisibility(View.VISIBLE);
                    String mSaveZipFile = DownloadManager.mSaveDirPath + zip_name;
                    String url = Constants.imageURL + "zip/" + zip_name;
                    downloadzip(mSaveZipFile, url, v, sceneTypeAdapter.getItem(position).get("id") + "", sceneTypeAdapter.getItem(position).get("time") + "");
                }

            }*/
        });
    }
    public void showDownAll(){
        if(TextUtils.isEmpty(tempTimer)){
            return;
        }
        if(tempTimer.equals(Config.getDownLoad()) ) {
            MyToast.show(getActivity(),getString(R.string.downloader));
        }else {
            new YesNoDialog.Builder(getActivity())
                    .setMessage(getString(R.string.downloadALL_title))
                    .setPositiveButton(getString(R.string.yes), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            if (!isdownload) {
                                    downloadALL();
                            }
                            dialog.dismiss();
                        }
                    })
                    .setNegativeButton(getString(R.string.no), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    })
                    .create().show();
        }
    }
    public void zhuceguangbo() {
        //  LocalBroadcastManager broadcastManager = LocalBroadcastManager.getInstance(getActivity());
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.lfy.update");//建议把它写一个公共的变量，这里方便阅读就不写了。
        mItemViewListClickReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                dbChildList = cL_InviteMessgeDao.getChildByCategroyId(categroyId);

                if (dbChildList.size() > 0) {
                    mList.clear();
                    for (int i = 0; i < dbChildList.size(); i++) {
                        HashMap<String, Object> map = new HashMap<String, Object>();
                        map.put("text", dbChildList.get(i).getName());
                        map.put("id", dbChildList.get(i).getId());
                        map.put("downLoadSize", dbChildList.get(i).getSize());
                        map.put("downLoadCount", dbChildList.get(i).getRemark());//getDownload_num()
                        map.put("child_img_url", dbChildList.get(i).getImagepath());
                        map.put("isneedUpdate", dbChildList.get(i).getIsneedUpdate());
                        map.put("zip_name", dbChildList.get(i).getZip_name());
                        map.put("download_type", dbChildList.get(i).getDownload_type());
                        map.put("time", dbChildList.get(i).getCreate_time());

                        mList.add(map);
                    }
                }
                sceneTypeAdapter.notifyDataSetChanged();
            }
        };
        getActivity().registerReceiver(mItemViewListClickReceiver, intentFilter);
    }

    private int allmListCount = 0;
    private boolean isdownload = false;

    private void downloadALL() {
        Toast.makeText(getActivity(), getString(R.string.downing_all_scene), Toast.LENGTH_SHORT).show();
        isdownload = true;
        allmListCount = 0;
        if (mList != null && mList.size() > 0) {
            downOne();
        }
    }
    public void bigMAXTimer(List<Child> childList){
        if(childList!=null&&childList.size()>0) {
            for (int i = 0; i < childList.size(); i++) {
                tempTimer = getBigTimer(tempTimer, childList.get(i).getCreate_time());
            }
        }
    }
    private String getBigTimer(String before,String now){
        if(TextUtils.isEmpty(before)){
            return now;
        }
        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        try {
            Date date1 = sd.parse(before);
            Date date2 = sd.parse(now);
            long s1 = date1.getTime() ;//时间的毫秒
            long s2 = date2.getTime();
            if(s1>s2){
                return  before;
            }else{
                return now;
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return  "";
    }
    public void downOne() {
        String zip_name = mList.get(allmListCount).get("zip_name").toString();
        String mSaveZipFile = DownloadManager.mSaveDirPath + zip_name;
        String url = Constants.imageURL + "zip/" + zip_name;
        downloadzipOne(mSaveZipFile, url, mList.get(allmListCount).get("id") + "", mList.get(allmListCount).get("time") + "", mList.get(allmListCount).get("text") + "");
    }

    public void downloadzipOne(final String mSaveZipFile, final String url, final String chilid, final String time, final String name) {
        DownloadManager.getInstance().download(DownloadManager.TRANSLATION, mSaveZipFile, url, new com.duowan.mobile.netroid.Listener<Void>() {
            @Override
            public void onSuccess(Void response) {
                // 将下载的zip文件解压缩到 DownloadManager.mSaveTranslateDirPath 目录
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Log.d("debug", "正在解压缩...");
                            UnzipFromDir.unZip(getActivity(), mSaveZipFile, DownloadManager.mSaveTranslateDirPath, true);
                            Log.d("debug", "解压缩文件完成! url=" + url);
                            if (new File(mSaveZipFile).exists())
                                new File(mSaveZipFile).delete();
                            Log.d("debug", "删除源文件完成!");
                        } catch (Exception e) {
                            e.printStackTrace();
                            Log.d("debug", "发生错误 ：" + e.toString());
                        }
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                              /*  ImageView down_img_id= (ImageView) v.findViewById(R.id.down_img_id);
                                down_img_id.setVisibility(View.VISIBLE);
                                TextView  jindu= (TextView) v.findViewById(R.id.jindu_id);
                                jindu.setVisibility(View.GONE);*/
                                cL_InviteMessgeDao.downloadOK(chilid, time);

                                // 更新界面UI
                                Toast.makeText(getActivity(), name + getString(R.string.downLoad_and_uncompress_ok), Toast.LENGTH_SHORT).show();
                                getActivity().sendBroadcast(new Intent("com.lfy.update"));
                                allmListCount++;
                                if (allmListCount >= mList.size()) {
                                    Toast.makeText(getActivity(), getString(R.string.downLoad_all_scene_ok), Toast.LENGTH_SHORT).show();
                                    isdownload = false;
                                    Config.setDownLoad(tempTimer);
                                } else {
                                    downOne();
                                }
                            }
                        });
                    }
                }).start();
            }

            @Override
            public void onProgressChange(long fileSize, long downloadedSize) {

            }
        });
    }

    public void downloadzip(final String mSaveZipFile, final String url, final View v, final String chilid, final String time) {
        DownloadManager.getInstance().download(DownloadManager.TRANSLATION, mSaveZipFile, url, new com.duowan.mobile.netroid.Listener<Void>() {
            @Override
            public void onSuccess(Void response) {
                // 将下载的zip文件解压缩到 DownloadManager.mSaveTranslateDirPath 目录
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Log.d("debug", "正在解压缩...");
                            UnzipFromDir.unZip(getActivity(), mSaveZipFile, DownloadManager.mSaveTranslateDirPath, true);
                            Log.d("debug", "解压缩文件完成! url=" + url);
                            if (new File(mSaveZipFile).exists())
                                new File(mSaveZipFile).delete();
                            Log.d("debug", "删除源文件完成!");
                        } catch (Exception e) {
                            e.printStackTrace();
                            Log.d("debug", "发生错误 ：" + e.toString());
                        }
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                              /*  ImageView down_img_id= (ImageView) v.findViewById(R.id.down_img_id);
                                down_img_id.setVisibility(View.VISIBLE);
                                TextView  jindu= (TextView) v.findViewById(R.id.jindu_id);
                                jindu.setVisibility(View.GONE);*/
                                cL_InviteMessgeDao.downloadOK(chilid, time);

                                // 更新界面UI
                                Toast.makeText(getActivity(), getString(R.string.downLoad_and_uncompress_ok), Toast.LENGTH_SHORT).show();
                                getActivity().sendBroadcast(new Intent("com.lfy.update"));
                            }
                        });
                    }
                }).start();
            }

            @Override
            public void onProgressChange(long fileSize, long downloadedSize) {
                /*TextView jindu = (TextView) v.findViewById(R.id.jindu_id);
                if (fileSize == downloadedSize) {
                    jindu.setText(getString(R.string.uncompressing));
                } else {
                    jindu.setText(getString(R.string.downing) + (int) (((float) downloadedSize / fileSize) * 100) + "%");
                }*/
                // 更新界面UI
                Log.d("debug", "fileSize = " + fileSize + "  downloadedSize= " + downloadedSize);
            }
        });
    }

    public void getchildCategroyFromServer( final Context mContext) {
        NetHelper.getchildCategroyFromServer(getActivity(),request_categroy, new NetUtils.NetCallBack<ServiceResult>() {
                    @Override
                    public void success(ServiceResult rspData) {
                          CategroyEntity info= (CategroyEntity) rspData;
                            int code=info.getRetcode();
                        List<Child> data=info.getData();
                        String message=info.getMessage();
                         if (code == 0) {
                            if (null != data) {
                                bigMAXTimer(data);
                                //获取need更新
                                cL_InviteMessgeDao.getUpdateListIsNeed(data, dbChildList);
                                cL_InviteMessgeDao.saveChildCategroy(categroyId, data);
                                if (dbChildList.size() == 0) {
                                    mList.clear();
                                    for (int i = 0; i < data.size(); i++) {
                                        HashMap<String, Object> map = new HashMap<String, Object>();
                                        map.put("text", data.get(i).getName());
                                        map.put("id", data.get(i).getId());
                                        map.put("downLoadSize", data.get(i).getSize());
                                        map.put("downLoadCount", data.get(i).getRemark());
                                        map.put("child_img_url", data.get(i).getImagepath());
                                        map.put("isneedUpdate", data.get(i).getIsneedUpdate());
                                        map.put("zip_name", data.get(i).getZip_name());
                                        map.put("download_type", data.get(i).getDownload_type());
                                        map.put("time", data.get(i).getCreate_time());
                                        mList.add(map);
                                    }
                                }
                            }else{
                                Toast.makeText(mContext, getString(R.string.get_scene_error),
                                        Toast.LENGTH_LONG).show();
                            }
                        }else{
                             Toast.makeText(mContext, message, Toast.LENGTH_LONG)
                                     .show();
                         }
                        if (dbChildList.size() == 0)
                            sceneTypeAdapter.notifyDataSetChanged();
                    }

                    @Override
                    public void failed(String msg) {
                        Toast.makeText(mContext, msg,
                                Toast.LENGTH_LONG).show();

                    }
                }, CategroyEntity.class);
    }
}
